package com.xuwei.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        //允许访问/login
        if(url.indexOf("/login")>=0){
            return true;
        }
        HttpSession session = request.getSession();
        System.out.println(session.getAttribute("user"));
        if(session.getAttribute("user")!=null) {
            System.out.println("2");
            // 登录成功不拦截
            return true;
        }else {
            // 拦截后进入登录页面
            System.out.println(request.getContextPath());
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }

    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HttpSession session = request.getSession();
//        System.out.println(session.getAttribute("user"));
//        if(session.getAttribute("user")!=null) {
//            // 登录成功不拦截
//            System.out.println("2");
//        }else {
//            // 拦截后进入登录页面
//            System.out.println(request.getContextPath());
//            response.sendRedirect(request.getContextPath()+"/login.jsp");
//
//        }

   // }
}
